import { reqLogin } from "../../request/api";
//初始值
const initState = {
  //初始化user
  user: {
    phone: "",
    password: "",
  },
  //用户信息
  info: sessionStorage.getItem('info')?JSON.parse(sessionStorage.getItem('info')):{},
};

//actionTypes
const types = {
  //修改user type
  CHANGE_USER: "LOGIN_CHANGE_USER",
  //修改info
  CHANGE_INFO: "LOGIN_CHANGE_INFO",
};

//reducer 修改数据
const reducer = (state = initState, action) => {
  switch (action.type) {
    // 修改user的reducer
    case types.CHANGE_USER:
      // {type:types.CHANGE_USER,key:"phone",value:""}
      return {
        ...state,
        user: {
          ...state.user,
          [action.key]: action.value,
        },
      };
    //修改info
    case types.CHANGE_INFO:
      return {
        ...state,
        info: action.info,
      };
    default:
      return state;
  }
};
//actionCreators组件派发的动作
export const actions = {
  //修改user的action
  changeUser: (key, value) => ({ type: types.CHANGE_USER, key, value }),
  //修改info
  changeInfo: (info) => {
    if (info.token) {
      //存
      sessionStorage.setItem("info", JSON.stringify(info));
    } else {
      //删
      sessionStorage.removeItem("info");
    }
    return { type: types.CHANGE_INFO, info };
  },
  //登录请求
  reqLogin: (history) => (dispatch, getState) => {
    let { user } = getState().login;
    reqLogin(user).then((res) => {
      if (res.data.code === 200) {
          //存信息
          dispatch(actions.changeInfo(res.data.list))

          //跳页面
          history.push('/index/home')
      }
    });
  },
};

//selectors导出数据
//导出user
export const getUser = (state) => state.login.user;
//导出info

export const getInfo = (state) => state.login.info;
export default reducer;
